'use strict';
angular.module('app.controllers')
    .controller('AdminCtrl', function($scope, $state, ngDialog, $window, HrService, NgTableParams, HotelService) {
        var vm = this;
        $scope.role = $window.sessionStorage.subrole;
        $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        vm.year = $window.sessionStorage.year;
        vm.month = $window.sessionStorage.month;
        vm.region = { id: 0 };
        vm.cluster = { id: 0 };

        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.regionChange = function() {
            if (vm.region == null) {
                vm.region = { id: 0 };
                vm.cluster = { id: 0 };
            } else {
                HotelService.getClusters(vm.region.id).then(function(ret) {
                    $scope.clusters = ret.data.value;
                    vm.loadData();
                })
            }
            if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
                vm.loadData();
            }
            if (vm.cluster == null) {
                vm.cluster = { id: 0 };
            }
        }

        vm.loadData = function() {
            if (vm.region == null) {
                vm.region = { id: 0 };
            }
            HrService.turnoverLeaderSummary(vm.year, vm.month).then(function(ret) {
                vm.result2 = ret.data.value.list;
            });

            HrService.turnoverDepartReportGet({
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }).then(function(ret) {
                vm.departResult = ret.data.value;
                vm.tableParams = new NgTableParams({
                    count: 10
                }, {
                    dataset: vm.departResult
                });
            })

            HrService.turnoverPeriodReportGet({
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }).then(function(ret) {
                vm.periodResult = ret.data.value;
                vm.tableParams2 = new NgTableParams({
                    count: 10
                }, {
                    dataset: vm.periodResult
                });
            })

            HrService.turnoverBandReportGet({
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }).then(function(ret) {
                vm.bandResult = ret.data.value;
                vm.tableParams3 = new NgTableParams({
                    count: 10
                }, {
                    dataset: vm.bandResult
                });
            })

            HrService.turnoverInterviewSummaryType({
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }).then(function(ret) {
                vm.sumType = ret.data.value;
                var typeload = {
                    name: 'Exit Interview',
                    datapoints: []
                };
                angular.forEach(vm.sumType, function(value, key) {
                    if (value.type == 'job') {
                        typeload.datapoints.push({
                            x: 'Job',
                            y: value.value
                        });
                    } else if (value.type == 'personal') {
                        typeload.datapoints.push({
                            x: 'Personal',
                            y: value.value
                        });
                    } else if (value.type == 'other') {
                        typeload.datapoints.push({
                            x: 'Others',
                            y: value.value
                        });
                    }
                });
                $scope.data3 = [typeload];
            });

            HrService.turnoverInterviewSummaryTop({
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }).then(function(ret) {
                if (ret.data.value.length > 0) {
                    vm.sumTop = ret.data.value;
                    var pageload = {
                        name: 'YTD Top 5 resignation reasons',
                        datapoints: []
                    };
                    angular.forEach(vm.sumTop, function(value, key) {
                        pageload.datapoints.push({
                            x: value.type,
                            y: value.value
                        });
                    })
                    $scope.data = [pageload];

                    var topreason = {
                        name: 'Top3 Reason',
                        datapoints: [{
                            x: vm.sumTop[0].type,
                            y: vm.sumTop[0].value
                        }, {
                            x: vm.sumTop[1].type,
                            y: vm.sumTop[1].value
                        }, {
                            x: vm.sumTop[2].type,
                            y: vm.sumTop[2].value
                        }]
                    };
                    $scope.data2 = [topreason];
                }


            })
        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();

        }

        $scope.config = {
            title: '',
            subtitle: '',
            debug: false,
            showXAxis: true,
            showYAxis: true,
            showLegend: true,
            calculable: true,
            // theme: 'shine',
            stack: false,
            toolbox: {
                show: true,
                feature: {
                    //mark : {show: true},
                    dataView: {
                        show: true,
                        readOnly: false
                    },
                    restore: {
                        show: true
                    },
                    saveAsImage: {
                        show: true
                    }
                }
            },
        };
        $scope.configBar = {
            title: '',
            subtitle: '',
            debug: false,
            showXAxis: true,
            showYAxis: true,
            showLegend: true,
            calculable: true,
            // theme: 'shine',
            stack: false,
            xAxis: {
                axisLabel: {
                    interval: 0,
                    // rotate: -10
                }
            },
            toolbox: {
                show: true,
                feature: {
                    //mark : {show: true},
                    dataView: {
                        show: true,
                        readOnly: false
                    },
                    restore: {
                        show: true
                    },
                    saveAsImage: {
                        show: true
                    }
                }
            },
        };

    })
    .controller('AdminRecognitionCtrl', function($scope, $state, ngDialog, $window, HrService, NgTableParams, HotelService) {
        var vm = this;
        vm.year = $window.sessionStorage.year;
        vm.month = $window.sessionStorage.month;
        $scope.role = $window.sessionStorage.subrole;
        $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        vm.region = { id: 0 };
        vm.cluster = { id: 0 };

        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.regionChange = function() {
            if (vm.region == null) {
                vm.region = { id: 0 };
                vm.cluster = { id: 0 };
            } else {
                HotelService.getClusters(vm.region.id).then(function(ret) {
                    $scope.clusters = ret.data.value;
                    vm.loadData();
                })
            }
            if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
                vm.loadData();
            }
            if (vm.cluster == null) {
                vm.cluster = { id: 0 };
            }
        }

        vm.loadData = function() {
            var sendbody = {
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }
            HrService.recognitionReportGet(sendbody).then(function(ret) {
                vm.result = ret.data.value;
                vm.tableParams = new NgTableParams({
                    count: 25
                }, {
                    dataset: vm.result,
                    counts: []
                });
            })
        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();

        }

    })

.controller('AdminFeedbackCtrl', function($scope, $state, ngDialog, $window, HrService, NgTableParams, HotelService) {
    var vm = this;
    vm.year = $window.sessionStorage.year;
    vm.month = $window.sessionStorage.month;
    $scope.role = $window.sessionStorage.subrole;
    $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
    $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
    vm.region = { id: 0 };
    vm.cluster = { id: 0 };
    if (!$scope.regions) {
        $scope.regions = [];
        HotelService.getRegions().then(function(ret) {
            if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                angular.forEach(ret.data.value, function(value, key) {
                    if ($window.sessionStorage.region == value.name) {
                        $scope.regions.push(value);
                        vm.region.id = value.id;
                        vm.regionChange();
                    }
                })
            } else {
                $scope.regions = ret.data.value;

            }
        })
    }

    vm.regionChange = function() {
        if (vm.region == null) {
            vm.region = { id: 0 };
            vm.cluster = { id: 0 };
        } else {
            HotelService.getClusters(vm.region.id).then(function(ret) {
                $scope.clusters = ret.data.value;
                vm.loadData();
            })
        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();
        }
        if (vm.cluster == null) {
            vm.cluster = { id: 0 };
        }
    }
    vm.loadData = function() {
        var sendbody = {
            year: vm.year,
            month: vm.month,
            region: vm.region.id,
            cluster: vm.cluster ? vm.cluster.id : 0
        }
        HrService.feedbackReportGet(sendbody).then(function(ret) {
            vm.result = ret.data.value;
            vm.tableParams = new NgTableParams({
                count: 25
            }, {
                dataset: vm.result,
                counts: []
            });
        })
    }
    if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
        vm.loadData();

    }

})

.controller('AdminRecruitCtrl', function($scope, $state, ngDialog, $window, HrService, HotelService) {
        var vm = this;
        vm.year = $window.sessionStorage.year;
        vm.month = $window.sessionStorage.month;
        $scope.role = $window.sessionStorage.subrole;
        $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        vm.region = { id: 0 };
        vm.cluster = { id: 0 };
        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.regionChange = function() {
            if (vm.region == null) {
                vm.region = { id: 0 };
                vm.cluster = { id: 0 };
            } else {
                HotelService.getClusters(vm.region.id).then(function(ret) {
                    $scope.clusters = ret.data.value;
                    vm.loadData();
                })
            }
            if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
                vm.loadData();
            }
            if (vm.cluster == null) {
                vm.cluster = { id: 0 };
            }
        }
        vm.loadData = function() {
            HrService.recruitReportGet(2016, 1, vm.region.id, vm.cluster == null ? 0 : vm.cluster.id).then(function(ret) {

                vm.sourceApp = ret.data.value.sourceApp;
                vm.sourceNew = ret.data.value.sourceNew;
                vm.convention = ret.data.value.conventionNew;
                var data1 = {
                    name: 'Source of Applicants',
                    datapoints: []
                };
                angular.forEach(vm.sourceApp, function(value, key) {
                    if (value.type != 'No. of employess recruited are the ones who return to their hometown') {
                        data1.datapoints.push({
                            x: value.type,
                            y: value.value
                        });
                    }
                })
                $scope.data1 = [data1];
                var data2 = {
                    name: 'Source of New Comers',
                    datapoints: []
                };
                angular.forEach(vm.sourceNew, function(value, key) {
                    if (value.type != 'No. of employess recruited are the ones who return to their hometown') {
                        data2.datapoints.push({
                            x: value.type,
                            y: value.value
                        });
                    }
                })
                $scope.data2 = [data2];
                var data3 = {
                    name: 'Source of New Comers Convention Rate',
                    datapoints: []
                };
                angular.forEach(vm.convention, function(value, key) {
                    if (value.type != 'No. of employess recruited are the ones who return to their hometown') {
                        data3.datapoints.push({
                            x: value.type,
                            y: value.value / 10000
                        });
                    }
                })
                $scope.data3 = [data3];
                $scope.config = {
                    title: 'Pie Chart',
                    subtitle: 'Pie Chart',
                    debug: false,
                    showXAxis: true,
                    showYAxis: true,
                    showLegend: true,
                    calculable: true,
                    stack: false,
                    forceClear: true,
                    emptyMsg: 'No Data',
                    errorMsg: 'No Data',
                    toolbox: {
                        show: true,
                        feature: {
                            //mark : {show: true},
                            dataView: {
                                show: true,
                                readOnly: false
                            },
                            restore: {
                                show: true
                            },
                            saveAsImage: {
                                show: true
                            }
                        }
                    },
                };

            });
        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();

        }


    })
    .controller('AdminStaffCtrl', function($scope, $state, ngDialog, $window, HrService, NgTableParams, HotelService) {
        var vm = this;
        vm.year = $window.sessionStorage.year;
        vm.month = $window.sessionStorage.month;
        $scope.role = $window.sessionStorage.subrole;
        $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        vm.region = { id: 0 };
        vm.cluster = { id: 0 };
        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.regionChange = function() {
            if (vm.region == null) {
                vm.region = { id: 0 };
                vm.cluster = { id: 0 };
            } else {
                HotelService.getClusters(vm.region.id).then(function(ret) {
                    $scope.clusters = ret.data.value;
                    vm.loadData();
                })
            }
            if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
                vm.loadData();
            }
            if (vm.cluster == null) {
                vm.cluster = { id: 0 };
            }
        }


        vm.loadData = function() {
            var sendBody = {
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }
            HrService.staffingReportGet(sendBody).then(function(ret) {
                vm.result = ret.data.value;
                vm.tableParams = new NgTableParams({
                    count: 25
                }, {
                    dataset: vm.result,
                    counts: []
                });
            })
        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();

        }

    })
    .controller('AdminDirectoryCtrl', function($scope, $state, ngDialog, $window, HrService, NgTableParams, HotelService) {
        var vm = this;
        vm.year = $window.sessionStorage.year;
        vm.month = $window.sessionStorage.month;
        $scope.role = $window.sessionStorage.subrole;
        $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        vm.region = { id: 0 };
        vm.cluster = { id: 0 };
        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.regionChange = function() {
            if (vm.region == null) {
                vm.region = { id: 0 };
                vm.cluster = { id: 0 };
            } else {
                HotelService.getClusters(vm.region.id).then(function(ret) {
                    $scope.clusters = ret.data.value;
                    vm.loadData();
                })
            }
            if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
                vm.loadData();
            }
            if (vm.cluster == null) {
                vm.cluster = { id: 0 };
            }
        }

        vm.loadData = function() {
            var sendBody = {
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }
            HrService.directoryReportGet(sendBody).then(function(ret) {
                vm.result = ret.data.value;
                vm.tableParams = new NgTableParams({
                    count: 25
                }, {
                    dataset: vm.result,
                    counts: []
                });
            })
        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();

        }

    })
    .controller('AdminPathwayCtrl', function($scope, $state, ngDialog, $window, HrService, NgTableParams, HotelService) {
        var vm = this;
        vm.year = $window.sessionStorage.year;
        vm.month = $window.sessionStorage.month;
        $scope.role = $window.sessionStorage.subrole;
        $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        vm.region = { id: 0 };
        vm.cluster = { id: 0 };
        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.regionChange = function() {
            if (vm.region == null) {
                vm.region = { id: 0 };
                vm.cluster = { id: 0 };
            } else {
                HotelService.getClusters(vm.region.id).then(function(ret) {
                    $scope.clusters = ret.data.value;
                    vm.loadData();
                })
            }
            if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
                vm.loadData();
            }
            if (vm.cluster == null) {
                vm.cluster = { id: 0 };
            }
        }
        vm.loadData = function() {
            var sendBody = {
                year: vm.year,
                month: vm.month,
                region: vm.region.id,
                cluster: vm.cluster ? vm.cluster.id : 0
            }
            HrService.pathwayReportGet(sendBody).then(function(ret) {
                vm.result = ret.data.value;
                // vm.tableParams1 = new NgTableParams({
                //     count: 25
                // }, {
                //     dataset: vm.result.sm,
                //     counts: []
                // });
                vm.tableParams2 = new NgTableParams({
                    count: 25
                }, {
                    dataset: vm.result.hr,
                    counts: []
                });
                vm.total = {
                    staffNo: 0,
                    cpJoinYtd: 0,
                    elearnYtd: 0,
                    pdpYtd: 0,
                    promotionYtd: 0,
                    moveYtd: 0
                };
                angular.forEach(vm.result.hr, function(value, key) {
                        vm.total.staffNo += value.staffNo;
                        vm.total.cpJoinYtd += value.cpJoinYtd;
                        vm.total.elearnYtd += value.elearnYtd;
                        vm.total.pdpYtd += value.pdpYtd;
                        vm.total.moveYtd += value.moveYtd;
                        vm.total.promotionYtd += value.promotionYtd;
                    })
                    // vm.tableParams3 = new NgTableParams({
                    //     count: 25
                    // }, {
                    //     dataset: vm.result.finance,
                    //     counts: []
                    // });
                    // vm.tableParams4 = new NgTableParams({
                    //     count: 25
                    // }, {
                    //     dataset: vm.result.fb,
                    //     counts: []
                    // });
                    // vm.tableParams5 = new NgTableParams({
                    //     count: 25
                    // }, {
                    //     dataset: vm.result.all,
                    //     counts: []
                    // });
            })
        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();

        }

    })
    .controller('AdminPeopleCtrl', function($scope, $state, ngDialog, $window, HrService, NgTableParams, HotelService) {
        var vm = this;
        vm.year = $window.sessionStorage.year;
        vm.month = $window.sessionStorage.month;
        $scope.role = $window.sessionStorage.subrole;
        $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        vm.region = { id: 0 };
        vm.cluster = { id: 0 };
        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.regionChange = function() {
            if (vm.region == null) {
                vm.region = { id: 0 };
                vm.cluster = { id: 0 };
            } else {
                HotelService.getClusters(vm.region.id).then(function(ret) {
                    $scope.clusters = ret.data.value;
                    vm.loadData();
                })
            }
            if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
                vm.loadData();
            }
            if (vm.cluster == null) {
                vm.cluster = { id: 0 };
            }
        }

        vm.clusterChange = function() {
            vm.loadData();
        }

        vm.viewDetail = function(ret, current) {
            $scope.ret = ret;
            $scope.current = current;
            ngDialog.open({
                template: 'views/admin/people-detail.html',
                ariaAuto: false,
                className: 'ngdialog-theme-plain custom-width',
                scope: $scope,
                controller: 'AdminPeopleDetailCtrl',
                controllerAs: 'vm',
                preCloseCallback: function(value) {
                    vm.loadData();
                    return true;
                }
            })
        }

        vm.viewVacancyDetail = function(ret, current, status) {
            $scope.ret = ret;
            $scope.current = current;
            if (status == 1) {
                $scope.status = ["warning", "danger", "purple", "ok"]
            } else {
                $scope.status = ["danger"]
            }
            ngDialog.open({
                template: 'views/admin/people-vacancy-detail.html',
                ariaAuto: false,
                className: 'ngdialog-theme-plain custom-width2',
                scope: $scope,
                controller: 'AdminPeopleVacancyDetailCtrl',
                controllerAs: 'vm',
                preCloseCallback: function(value) {
                    vm.loadData();
                    return true;
                }
            })
        };

        vm.loadData = function() {
            var sendBody = {
                year: vm.year,
                month: vm.month
            }
            if (vm.region && vm.region.id) {
                sendBody.region = vm.region.id
            } else {
                sendBody.region = ''
            }
            if (vm.cluster && vm.cluster.id) {
                sendBody.cluster = vm.cluster.id
            } else {
                sendBody.cluster = ''
            }
            HrService.peopleReportGet(sendBody).then(function(ret) {
                vm.result = ret.data.value;
                vm.tableParams = new NgTableParams({
                    count: 25
                }, {
                    dataset: vm.result,
                    counts: []
                });
            });

            HrService.peopleReportTopGet(sendBody).then(function(ret) {
                vm.total2 = {
                    data: [{
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }]
                }
                vm.tableParams2 = new NgTableParams({
                    count: 25
                }, {
                    dataset: ret.data.value,
                    counts: []
                });
                angular.forEach(ret.data.value, function(pvalue, key) {
                    angular.forEach(pvalue.data, function(value, key) {
                        if (value.vacantStatus == 'purple') {
                            vm.total2.data[key].number++;
                        }

                    });

                })

            });
            var vSendBody = {
                year: vm.year,
                month: vm.month,
                status: ["warning", "danger", "purple", "ok"]
            }

            HrService.peopleVReportGet(vSendBody).then(function(ret) {
                vm.total3 = {
                    data: [{
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }]
                }
                vm.tableParams3 = new NgTableParams({
                    count: 25
                }, {
                    dataset: ret.data.value,
                    counts: []
                });
                angular.forEach(ret.data.value, function(pvalue, key) {
                    angular.forEach(pvalue.data, function(value, key) {
                        vm.total3.data[key].number += value.number;
                    });

                })
            })

            var vSendBody2 = {
                year: vm.year,
                month: vm.month,
                status: ["danger"]
            }

            HrService.peopleVReportGet(vSendBody2).then(function(ret) {
                vm.total4 = {
                    data: [{
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }, {
                        number: 0
                    }]
                }
                vm.tableParams4 = new NgTableParams({
                    count: 25
                }, {
                    dataset: ret.data.value,
                    counts: []
                });
                angular.forEach(ret.data.value, function(pvalue, key) {
                    angular.forEach(pvalue.data, function(value, key) {
                        vm.total4.data[key].number += value.number;
                    });

                })
            })

        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();

        }

    })
    .controller('AdminPeopleVacancyDetailCtrl', function($scope, $window, HrService, NgTableParams, ngDialog) {
        var vm = this;
        vm.current = {};
        vm.current.position = $scope.current.position;
        vm.current.regionId = $scope.ret.id;
        vm.current.status = $scope.status;
        vm.ret = $scope.ret;
        vm.diversityOptions = ['Foreign Expatriate', 'Local Expatriate', 'Local hire'];

        vm.loadData=function () {
            HrService.peopleVacancyDetailGet(vm.current).then(function(ret) {
            vm.tableParams = new NgTableParams({
                count: 25
            }, {
                dataset: ret.data.value,
                counts: []
            });
        })
        }
        vm.loadData();
        

        vm.viewDetail = function(ret, current) {
            $scope.ret = ret;
            $scope.current = current;
            ngDialog.open({
                template: 'views/admin/people-detail.html',
                ariaAuto: false,
                className: 'ngdialog-theme-plain custom-width',
                scope: $scope,
                controller: 'AdminPeopleDetailCtrl',
                controllerAs: 'vm',
                preCloseCallback: function(value) {
                    vm.loadData();
                    return true;
                }
            })
        }

        vm.update = function() {
            HrService.peopleSingleUpdate(vm.current).then(function(ret) {
                if (ret.code == 'FAILED') {
                    alert(ret.reason);
                    return false;
                } else {
                    vm.msg = 'Saved.' + new Date();
                }
            })
        }

        vm.checkVacant = function(ret, hotel) {
            if (!ret.vacantDate || ret.vacantDate == '') {
                ret.vacantStatus = '';
            } else {
                var date = new Date(ret.vacantDate);
                if (hotel.top) {
                    if ((new Date()) - date > 5184000000) { // 60 days
                        ret.vacantStatus = 'purple';
                    } else {
                        ret.vacantStatus = 'warning';
                    }
                } else {
                    if ((new Date()) - date > 7776000000) { // 90 days
                        ret.vacantStatus = 'danger';
                    } else {
                        ret.vacantStatus = 'warning';
                    }
                }
            }
            if (ret.comment == 'ok') {
                ret.vacantStatus = 'ok';
            }
        }

        $scope.today = function() {
            $scope.dt = new Date();
        };
        $scope.today();

        $scope.clear = function() {
            vm.current.name = '';
            $scope.dt = null;
        };
        $scope.open = function(ret, $event) {
            ret.opened = true;
        };

        $scope.setDate = function(year, month, day) {
            $scope.dt = new Date(year, month, day);
        };

        $scope.dateOptions = {
            formatYear: 'yy',
            startingDay: 1
        };

        $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
        $scope.format = $scope.formats[0];

        $scope.status = {
            opened: false
        };

        var tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        var afterTomorrow = new Date();
        afterTomorrow.setDate(tomorrow.getDate() + 2);
        $scope.events = [{
            date: tomorrow,
            status: 'full'
        }, {
            date: afterTomorrow,
            status: 'partially'
        }];

    })
    .controller('AdminPeopleDetailCtrl', function($scope, $window, HrService) {
        var vm = this;
        vm.current = $scope.current;
        vm.current.hotel = $scope.ret.hotel;
        vm.current.updateBy = 'Admin';
        vm.ret = $scope.ret;
        vm.diversityOptions = ['Foreign Expatriate', 'Local Expatriate', 'Local hire'];

        vm.update = function() {
            HrService.peopleSingleUpdate(vm.current).then(function(ret) {
                if (ret.code == 'FAILED') {
                    alert(ret.reason);
                    return false;
                } else {
                    vm.msg = 'Saved.' + new Date();
                }
            })
        }

        vm.checkVacant = function(ret, hotel) {
            if (!ret.vacantDate || ret.vacantDate == '') {
                ret.vacantStatus = '';
            } else {
                var date = new Date(ret.vacantDate);
                if (hotel.top) {
                    if ((new Date()) - date > 5184000000) { // 60 days
                        ret.vacantStatus = 'purple';
                    } else {
                        ret.vacantStatus = 'warning';
                    }
                } else {
                    if ((new Date()) - date > 7776000000) { // 90 days
                        ret.vacantStatus = 'danger';
                    } else {
                        ret.vacantStatus = 'warning';
                    }
                }
            }
            if (ret.comment == 'ok') {
                ret.vacantStatus = 'ok';
            }
        }

        $scope.today = function() {
            $scope.dt = new Date();
        };
        $scope.today();

        $scope.clear = function() {
            vm.current.name = '';
            $scope.dt = null;
        };
        $scope.open = function(ret, $event) {
            ret.opened = true;
        };

        $scope.setDate = function(year, month, day) {
            $scope.dt = new Date(year, month, day);
        };

        $scope.dateOptions = {
            formatYear: 'yy',
            startingDay: 1
        };

        $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
        $scope.format = $scope.formats[0];

        $scope.status = {
            opened: false
        };

        var tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        var afterTomorrow = new Date();
        afterTomorrow.setDate(tomorrow.getDate() + 2);
        $scope.events = [{
            date: tomorrow,
            status: 'full'
        }, {
            date: afterTomorrow,
            status: 'partially'
        }];

    })
    .controller('AdminSettingCtrl', function($scope, $http, HotelService) {
        var vm = this;
        $scope.years = [2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        var today = new Date();
        vm.year = today.getFullYear();
        vm.month = today.getMonth() + 1;

        function findElement(arr, propName, propValue) {
            var ret = [];
            for (var i = 0; i < arr.length; i++)
                if (arr[i][propName] == propValue)
                    ret.push(arr[i]);

            return ret;

            // will return undefined if not found; you could return a default instead
        }

        function updateElement(arr, replaceTo) {
            for (var i = 0; i < arr.length; i++) {
                for (var j = 0; j < replaceTo.length; j++) {
                    if (arr[i]["year"] == replaceTo[j]['year'] && arr[i]["month"] == replaceTo[j]['month'])
                        arr[i] = replaceTo[j];
                }
            }

            return arr;
        }
        HotelService.getCurrentMonth().then(function(ret) {
            vm.month = ret.data.value.month;
            vm.year = ret.data.value.year;
            vm.loadData();

        })
        vm.loadData = function() {

            HotelService.getSettings().then(function(response) {
                $scope.configure = response.data.value;
                vm.currentYear = findElement($scope.configure, 'year', vm.year);
            });
        }

        vm.loadData();

        vm.saveTable = function() {
            var sendbody = updateElement($scope.configure, vm.currentYear);
            HotelService.saveCurrentMonth(vm.year, vm.month).then(function(ret) {
                if (ret.code == 'FAILED') {
                    alert(ret.reason);
                    return false;
                }
                HotelService.saveSettings({
                    year: vm.year,
                    settings: vm.currentYear
                }).then(function(ret) {
                    if (ret.code == 'FAILED') {
                        alert(ret.reason);
                        return false;
                    } else {
                        vm.msg = 'Saved.' + new Date();
                        vm.loadData();
                    }
                })
            })

        }


    })
    .controller('AdminPreopenCtrl', function($scope, $state, ngDialog, $window, TrService, NgTableParams, HotelService, PreopenService, $location) {
        var vm = this;
        vm.month = $window.sessionStorage.month;
        vm.total = {
            complete: {
                hr: 0,
                tr: 0,
                total: 0
            }
        };
        vm.totalStaffNo = 0;
        vm.total4 = {
            data: [{
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }, {
                number: 0
            }]
        }
        HotelService.allPreopen().then(function(ret) {
            vm.result = ret.data;
            vm.tableParams5 = new NgTableParams({
                count: 25
            }, {
                dataset: vm.result
            });
        })
        PreopenService.completionSum().then(function(ret) {
            var hr = 0;
            var tr = 0;
            var hrAll = 0;
            var trAll = 0;
            angular.forEach(ret.data.value, function(value, key) {
                hr += parseInt(value.hrNow);
                tr += parseInt(value.trNow);
                hrAll += parseInt(value.hrAll);
                trAll += parseInt(value.trAll);
            })
            vm.total.complete.hr = hr / hrAll;
            vm.total.complete.tr = tr / trAll;
            vm.total.complete.total = (hr + tr) / (hrAll + trAll);
            vm.tableParams1 = new NgTableParams({
                count: 100
            }, {
                dataset: ret.data.value,
                counts: []
            });
        })
        PreopenService.ytdStaffNoSum().then(function(ret) {
            vm.tableParams2 = new NgTableParams({
                count: 100
            }, {
                dataset: ret.data.value,
                counts: []
            });
            angular.forEach(ret.data.value, function(value, key) {
                vm.totalStaffNo += value.staffNo
            })
        })
        PreopenService.recruitGet().then(function(ret) {
            vm.allHotelCount = ret.data.value.length;
            angular.forEach(ret.data.value, function(pvalue, key) {
                angular.forEach(pvalue.people, function(value, key) {
                    if (value.phase == 'On-board') {
                        vm.total4.data[key].number++;
                    }

                });

            })
            vm.tableParams6 = new NgTableParams({
                count: 100
            }, {
                dataset: ret.data.value,
                counts: []
            });
        });
        vm.viewVacancyDetail = function(ret, people, nouse) {
            $scope.ret = ret;
            $scope.people = people;

            ngDialog.open({
                template: 'views/admin/preopen-people-detail.html',
                ariaAuto: false,
                className: 'ngdialog-theme-plain custom-width2',
                scope: $scope
            })
        }

        vm.getPercentage = function(ret) {
            var count = 0;
            var total = 18;
            angular.forEach(ret, function(value, key) {
                if (value.phase == 'On-board') {
                    count++;
                }
            })
            return count / total;
        }

        vm.getPercentageAll = function(ret) {
            var count = 0;
            var total = 18 * vm.allHotelCount;
            angular.forEach(ret, function(value, key) {
                count += value.number;
            })
            return count / total;
        }


    })


.controller('AdminTrainingCtrl', function($scope, $state, ngDialog, $window, TrService, NgTableParams, HotelService, $location) {
    var vm = this;
    vm.year = $window.sessionStorage.year;
    vm.month = $window.sessionStorage.month;
    $scope.role = $window.sessionStorage.subrole;
    vm.host = $location.host();
    $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
    $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
    vm.region = { id: 0 };
    vm.cluster = { id: 0 };
    if (!$scope.regions) {
        $scope.regions = [];
        HotelService.getRegions().then(function(ret) {
            if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                angular.forEach(ret.data.value, function(value, key) {
                    if ($window.sessionStorage.region == value.name) {
                        $scope.regions.push(value);
                        vm.region.id = value.id;
                        vm.regionChange();
                    }
                })
            } else {
                $scope.regions = ret.data.value;

            }
        })
    }



    vm.reportlink = '/api/training/export/monthly/' + vm.year + '/';
    vm.reportlink2 = '/api/tr/sum/export/' + vm.year + '/' + vm.region.id;
    vm.reportlink3 = '/api/tr/sum/export/hotel/' + vm.year + vm.region.id;

    vm.regionChange = function() {
        if (vm.region == null) {
            vm.region = { id: 0 };
            vm.cluster = { id: 0 };
        } else {
            HotelService.getClusters(vm.region.id).then(function(ret) {
                $scope.clusters = ret.data.value;
                vm.loadData();
            })
        }
        if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
            vm.loadData();
        }
        if (vm.cluster == null) {
            vm.cluster = { id: 0 };
        }
        vm.reportlink = '/api/training/export/monthly/' + vm.year + '/';
        vm.reportlink2 = '/api/tr/sum/export/' + vm.year + '/' + vm.region.id;
        vm.reportlink3 = '/api/tr/sum/export/hotel/' + vm.year + vm.region.id;
    }

    vm.clusterChange = function() {
        vm.loadData();
    }

    vm.loadData = function() {
        var sendBody = {
            year: vm.year,
            month: vm.month,
            region: vm.region ? vm.region.id : 0
        }


        TrService.summaryReport(sendBody).then(function(ret) {
            vm.total1 = {
                ctc1: 0,
                ctc2: 90,
                ctc3: 0,
                ctcValid: 0,
                gtc1: 0,
                gtc2: 90,
                gtc3: 0,
                gtcValid: 0,
                mtd1: 0,
                mtd2: 90,
                mtd3: 0,
                mtdValid: 0,
                bsb1: 0,
                bsb2: 100,
                bsb3: 0,
                bsbValid: 0,
                lopm1: 0,
                lopm2: 70,
                lopm3: 0,
                lopmValid: 0,
                aldp1: 0,
                aldp2: 70,
                aldp3: 0,
                aldpValid: 0
            };
            vm.total2 = {
                ctc1: 0,
                ctc2: 75,
                ctcValid: 0,
                bi1: 0,
                bi2: 75,
                biValid: 0,
                gtc1: 0,
                gtc2: 75,
                gtcValid: 0,
                mlf1: 0,
                mlf2: 75,
                mlfValid: 0,
                mlo1: 0,
                mlo2: 75,
                mloValid: 0,
                mtd1: 0,
                mtd2: 75,
                mtdValid: 0,
                slf1: 0,
                slf2: 75,
                slfValid: 0,
                slo1: 0,
                slo2: 75,
                sloValid: 0,
                coach1: 0,
                coach2: 75,
                coachValid: 0
            };
            vm.total3 = {
                brand1: 0,
                brand2: 75,
                brandValid: 0,
                problem1: 0,
                problem2: 75,
                problemValid: 0,
                reward1: 0,
                reward2: 75,
                rewardValid: 0
            };
            vm.total4 = {
                coaching1: 0,
                coaching2: 70,
                coachingValid: 0,
                elearn1: 0,
                elearn2: 70,
                elearnValid: 0,
                learnDay1: 0,
                learnDay2: 70,
                learnDayValid: 0
            };
            angular.forEach(ret.data.value.training, function(value, key) {
                if (value.ctc != null) {
                    vm.total1.ctc1 += parseInt(value.ctc.tValue);
                    vm.total1.ctc3 += parseInt(value.ctc.hValue);
                    vm.total1.ctcValid += parseInt(value.ctc.validHotelNumber);
                }
                if (value.gtc != null) {
                    vm.total1.gtc1 += parseInt(value.gtc.tValue);
                    vm.total1.gtc3 += parseInt(value.gtc.hValue);
                    vm.total1.gtcValid += parseInt(value.gtc.validHotelNumber);
                }
                if (value.mtd != null) {
                    vm.total1.mtd1 += parseInt(value.mtd.tValue);
                    vm.total1.mtd3 += parseInt(value.mtd.hValue);
                    vm.total1.mtdValid += parseInt(value.mtd.validHotelNumber);
                }
                if (value.bsb != null) {
                    vm.total1.bsb1 += parseInt(value.bsb.tValue);
                    vm.total1.bsb3 += parseInt(value.bsb.hValue);
                    vm.total1.bsbValid += parseInt(value.bsb.validHotelNumber);
                }
                if (value.lopm != null) {
                    vm.total1.lopm1 += parseInt(value.lopm.tValue);
                    vm.total1.lopm3 += parseInt(value.lopm.hValue);
                    vm.total1.lopmValid += parseInt(value.lopm.validHotelNumber);
                }
                if (value.aldp != null) {
                    vm.total1.aldp1 += parseInt(value.aldp.tValue);
                    vm.total1.aldp3 += parseInt(value.aldp.hValue);
                    vm.total1.aldpValid += parseInt(value.aldp.validHotelNumber);
                }
            })
            vm.total1.ctc1 = (vm.total1.ctc1 / vm.total1.ctcValid) * 100;
            vm.total1.gtc1 = (vm.total1.gtc1 / vm.total1.gtcValid) * 100;
            vm.total1.mtd1 = (vm.total1.mtd1 / vm.total1.mtdValid) * 100;
            vm.total1.bsb1 = (vm.total1.bsb1 / vm.total1.bsbValid) * 100;
            vm.total1.lopm1 = (vm.total1.lopm1 / vm.total1.lopmValid) * 100;
            vm.total1.aldp1 = (vm.total1.aldp1 / vm.total1.aldpValid) * 100;
            vm.total1.ctc3 = (vm.total1.ctc3 / vm.total1.ctcValid) * 100;
            vm.total1.gtc3 = (vm.total1.gtc3 / vm.total1.gtcValid) * 100;
            vm.total1.mtd3 = (vm.total1.mtd3 / vm.total1.mtdValid) * 100;
            vm.total1.bsb3 = (vm.total1.bsb3 / vm.total1.bsbValid) * 100;
            vm.total1.lopm3 = (vm.total1.lopm3 / vm.total1.lopmValid) * 100;
            vm.total1.aldp3 = (vm.total1.aldp3 / vm.total1.aldpValid) * 100;

            angular.forEach(ret.data.value.manager, function(value, key) {
                if (value.ctc != null) {
                    vm.total2.ctc1 += parseInt(value.ctc.hValue);
                    vm.total2.ctcValid += parseInt(value.ctc.staff);
                }
                if (value.gtc != null) {
                    vm.total2.gtc1 += parseInt(value.gtc.hValue);
                    vm.total2.gtcValid += parseInt(value.gtc.staff);
                }
                if (value.mlf != null) {
                    vm.total2.mlf1 += parseInt(value.mlf.hValue);
                    vm.total2.mlfValid += parseInt(value.mlf.staff);
                }
                if (value.mlo != null) {
                    vm.total2.mlo1 += parseInt(value.mlo.hValue);
                    vm.total2.mloValid += parseInt(value.mlo.staff);
                }
                if (value.slf != null) {
                    vm.total2.slf1 += parseInt(value.slf.hValue);
                    vm.total2.slfValid += parseInt(value.slf.staff);
                }
                if (value.slo != null) {
                    vm.total2.slo1 += parseInt(value.slo.hValue);
                    vm.total2.sloValid += parseInt(value.slo.staff);
                }
                if (value.bi != null) {
                    vm.total2.bi1 += parseInt(value.bi.hValue);
                    vm.total2.biValid += parseInt(value.bi.staff);
                }
                if (value.coach != null) {
                    vm.total2.coach1 += parseInt(value.coach.hValue);
                    vm.total2.coachValid += parseInt(value.coach.staff);
                }
                if (value.mtd != null) {
                    vm.total2.mtd1 += parseInt(value.mtd.hValue);
                    vm.total2.mtdValid += parseInt(value.mtd.staff);
                }
            })
            vm.total2.ctc1 = (vm.total2.ctc1 / vm.total2.ctcValid) * 100;
            vm.total2.gtc1 = (vm.total2.gtc1 / vm.total2.gtcValid) * 100;
            vm.total2.mlf1 = (vm.total2.mlf1 / vm.total2.mlfValid) * 100;
            vm.total2.mlo1 = (vm.total2.mlo1 / vm.total2.mloValid) * 100;
            vm.total2.mtd1 = (vm.total2.mtd1 / vm.total2.mtdValid) * 100;
            vm.total2.slo1 = (vm.total2.slo1 / vm.total2.sloValid) * 100;
            vm.total2.slf1 = (vm.total2.slf1 / vm.total2.slfValid) * 100;
            vm.total2.bi1 = (vm.total2.bi1 / vm.total2.biValid) * 100;
            vm.total2.coach1 = (vm.total2.coach1 / vm.total2.coachValid) * 100;

            angular.forEach(ret.data.value.frontline, function(value, key) {
                if (value.brand != null) {
                    vm.total3.brand1 += parseInt(value.brand.hValue);
                    vm.total3.brandValid += parseInt(value.brand.staff);
                }
                if (value.problem != null) {
                    vm.total3.problem1 += parseInt(value.problem.hValue);
                    vm.total3.problemValid += parseInt(value.problem.staff);
                }
                if (value.reward != null) {
                    vm.total3.reward1 += parseInt(value.reward.hValue);
                    vm.total3.rewardValid += parseInt(value.reward.staff);
                }
            })
            vm.total3.brand1 = (vm.total3.brand1 / vm.total3.brandValid) * 100;
            vm.total3.problem1 = (vm.total3.problem1 / vm.total3.problemValid) * 100;
            vm.total3.reward1 = (vm.total3.reward1 / vm.total3.rewardValid) * 100;

            angular.forEach(ret.data.value.excom, function(value, key) {
                if (value.coaching != null) {
                    vm.total4.coaching1 += parseInt(value.coaching.hValue);
                    vm.total4.coachingValid += parseInt(value.coaching.staff);
                }
                if (value.elearn != null) {
                    vm.total4.elearn1 += parseInt(value.elearn.hValue);
                    vm.total4.elearnValid += parseInt(value.elearn.staff);
                }
                if (value.learnDay != null) {
                    vm.total4.learnDay1 += parseInt(value.learnDay.hValue);
                    vm.total4.learnDayValid += parseInt(value.learnDay.staff);
                }
            })
            vm.total4.coaching1 = (vm.total4.coaching1 / vm.total4.coachingValid) * 100;
            vm.total4.elearn1 = (vm.total4.elearn1 / vm.total4.elearnValid) * 100;
            vm.total4.learnDay1 = (vm.total4.learnDay1 / vm.total4.learnDayValid) * 100;


            vm.tableParams1 = new NgTableParams({
                count: 25
            }, {
                dataset: ret.data.value.training,
                counts: []
            });

            vm.tableParams2 = new NgTableParams({
                count: 25
            }, {
                dataset: ret.data.value.manager,
                counts: []
            });
            vm.tableParams3 = new NgTableParams({
                count: 25
            }, {
                dataset: ret.data.value.frontline,
                counts: []
            });
            vm.tableParams4 = new NgTableParams({
                count: 25
            }, {
                dataset: ret.data.value.excom,
                counts: []
            });
        })
        if (vm.region == null) {
            vm.region = { id: 0 };
        }

        HotelService.allByRegion(vm.region.id).then(function(ret) {
            vm.result2 = ret.data;
            vm.tableParams6 = new NgTableParams({
                count: 25
            }, {
                dataset: vm.result2
            });
        })
        vm.reportlink = '/api/training/export/monthly/' + vm.year + '/';

        vm.reportlink2 = '/api/tr/sum/export/' + vm.year + '/' + vm.region.id;
        vm.reportlink3 = '/api/tr/sum/export/hotel/' + vm.year + '/' + vm.region.id;

    }
    if ($window.sessionStorage.subrole != 'Sub-Region Admin') {
        vm.loadData();

    }


})

.controller('ProgressCtrl', function($scope, $state, ngDialog, $window, HotelService, NgTableParams) {
        var vm = this;
        vm.year = $window.sessionStorage.year;
        vm.month = $window.sessionStorage.month;
        $scope.role = $window.sessionStorage.subrole;
        //vm.host = $location.host();
        $scope.years = [2015, 2016, 2017, 2018, 2019, 2020];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.regionChange = function() {
            vm.cluster = null;
            vm.loadData();
            HotelService.getClusters(vm.region.id).then(function(ret) {
                $scope.clusters = ret.data.value;
            })
        }

        vm.clusterChange = function() {
            vm.loadData();
        }
        vm.progressNoStyle = function(number) {
            return 'width:' + number * 100 + '%;'
        }

        vm.total = { total: 0, submision: 0 };
        vm.loadData = function() {
            vm.total = { total: 0, submision: 0 };
            HotelService.getProgressSummary(vm.year, vm.month).then(function(ret) {
                vm.summary = ret.data.value;
                angular.forEach(vm.summary, function(value, key) {
                    vm.total.total += value.hotelNo;
                    vm.total.submision += value.count;
                })
            })
            HotelService.getProgressSummaryAll(vm.year, vm.month).then(function(ret) {
                vm.result = ret.data.value;
                vm.tableParams = new NgTableParams({
                    count: 25
                }, {
                    dataset: vm.result
                });
            })
        }
        vm.loadData();

    })
    .controller('HotelMgmtCtrl', function($scope, $state, ngDialog, $window, HotelService, NgTableParams, UserService) {
        var vm = this;
        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                $scope.regions = ret.data.value;
            })
        }
        vm.regionChange = function() {
            vm.cluster = null;
            HotelService.getClusters(vm.region.id).then(function(ret) {
                $scope.clusters = ret.data.value;
            })
        }
        vm.resetPassword = function(code) {
            ngDialog.openConfirm({
                template: '\
                    <p>Are you sure you want to Reset password for this hotel?</p>\
                    <div class="ngdialog-buttons">\
                        <button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog(0)">No</button>\
                        <button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="confirm(1)">Yes</button>\
                    </div>',
                plain: true
            }).then(function(value) {
                var user = {
                    'code': code,
                    'oldPassword': '',
                    'newPassword': hex_md5('88888888'),
                    'admin': true
                };
                UserService.changePwd(user).then(function(ret) {
                    if (ret.data.code != 1) {
                        alert(ret.data.value);
                    }
                })
            })

        }
        vm.loadData = function() {
            HotelService.all().then(function(ret) {
                vm.result = ret.data;
                vm.tableParams = new NgTableParams({
                    count: 25
                }, {
                    dataset: vm.result
                });
            })
        }
        vm.loadData();
        vm.deleteHotel = function(id) {
            ngDialog.openConfirm({
                template: '\
                    <p>Are you sure you want to Delete this hotel?</p>\
                    <div class="ngdialog-buttons">\
                        <button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog(0)">No</button>\
                        <button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="confirm(1)">Yes</button>\
                    </div>',
                plain: true
            }).then(function(value) {
                HotelService.deleteHotel(id).then(function() {
                    alert('删除酒店成功！');
                    vm.loadData();
                });
            })

        };

        vm.addHotel = function () {
            ngDialog.open({
                    template: 'views/admin/edit_hotel.html',
                    ariaAuto: false,
                    className: 'ngdialog-theme-plain custom-width',
                    controller: ['$scope', 'ngDialog', 'HotelService', function($scope, ngDialog, HotelService) {
                        $scope.hotel = {};
                        $scope.hotel.passowrd = '';
                        $scope.regions = [];
                        HotelService.getRegions().then(function(ret) {
                            $scope.regions = ret.data.value;
                            $scope.hotel.region=$scope.regions[0];
                            if ($scope.hotel.region.id != null) {
                                HotelService.getClusters($scope.hotel.region.id).then(function(ret) {
                                    $scope.clusters = ret.data.value;
                                })
                            }
                        });

                        $.extend($scope, {
                            regionChange: function(regionId) {
                                HotelService.getClusters(regionId).then(function(ret) {
                                    $scope.clusters = ret.data.value;
                                })
                            },
                            closeDialog: function() {
                                ngDialog.closeAll();
                            },

                            editHotel: function() {
                                $scope.hotel.regionId = $scope.hotel.region.id;
                                if ($scope.hotel.cluster == null) {
                                    alert("Please select a cluster!");
                                    return;
                                }
                                if ($scope.hotel.brand == null) {
                                    alert("Please select a Brand!");
                                    return;
                                }
                                if ($scope.hotel.type == null) {
                                    alert("Please select the Type!");
                                    return;
                                }
                                $scope.hotel.clusterId = $scope.hotel.cluster.id;

                                HotelService.saveHotel($scope.hotel).then(function(ret) {
                                    if (ret.data.code == 1) {
                                        alert(ret.data.value);
                                        return false;
                                    };
                                    alert("Add Successfully！");
                                    $scope.closeDialog();
                                    vm.loadData();
                                });
                            }
                        });
                    }],
                    scope: $scope
                });
        }

        vm.editHotel = function(hotel) {
            HotelService.get(hotel.id).then(function(ret) {
                $scope.hotel = ret.data.value;
                ngDialog.open({
                    template: 'views/admin/edit_hotel.html',
                    ariaAuto: false,
                    className: 'ngdialog-theme-plain custom-width',
                    controller: ['$scope', 'ngDialog', 'HotelService', function($scope, ngDialog, HotelService) {
                        $scope.hotel = hotel;
                        $scope.hotel.passowrd = '';
                        $scope.regions = [];
                        HotelService.getRegions().then(function(ret) {
                            $scope.regions = ret.data.value;
                            if (hotel.region.id != null) {
                                HotelService.getClusters(hotel.region.id).then(function(ret) {
                                    $scope.clusters = ret.data.value;
                                })
                            }
                        });

                        $.extend($scope, {
                            regionChange: function(regionId) {
                                HotelService.getClusters(regionId).then(function(ret) {
                                    $scope.clusters = ret.data.value;
                                })
                            },
                            closeDialog: function() {
                                ngDialog.closeAll();
                            },

                            editHotel: function() {
                                $scope.hotel.regionId = $scope.hotel.region.id;
                                if ($scope.hotel.cluster == null) {
                                    alert("Please select a cluster!");
                                    return;
                                }
                                $scope.hotel.clusterId = $scope.hotel.cluster.id;

                                HotelService.saveHotel($scope.hotel).then(function(ret) {
                                    if (ret.data.code == 1) {
                                        alert(ret.data.value);
                                        return false;
                                    };
                                    alert("Edit Successfully！");
                                    $scope.closeDialog();
                                    vm.loadData();
                                });
                            }
                        });
                    }],
                    scope: $scope
                });
            })

        };

        vm.createAdminUser = function() {
            $scope.user = {};
            ngDialog.open({
                template: 'views/admin/create_admin_user.html',
                ariaAuto: false,
                className: 'ngdialog-theme-plain custom-width',
                controller: ['$scope', 'ngDialog', function($scope, ngDialog) {
                    var postData = {};
                    var emailRegex = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g;

                    var mobileRegex = /^(13[0-9]{9})|(14[0-9])|(18[0-9])|(15[0-9][0-9]{8})$/;

                    $.extend($scope, {
                        closeDialog: function() {
                            ngDialog.closeAll();
                        },

                        checkFieldLength: function(field, start, end) {
                            return !(!field || field.length < start || field.length > end);
                        },

                        showFieldTooltip: function(selector) {
                            $(selector).popover('show');
                        },

                        closeFiledTooltip: function(selector) {
                            $(selector).popover('destroy');
                        },

                        closeAllTooltip: function() {
                            $scope.closeFiledTooltip('#password');
                            $scope.closeFiledTooltip('#re-password');
                            $scope.closeFiledTooltip('#email');
                            $scope.closeFiledTooltip('#mobile');
                        },

                        checkPassword: function() {
                            var user = $scope.user;
                            var password = user.password ? $.trim(user.password) : '';

                            postData['password'] = password;
                            return $scope.checkFieldLength(password, 3, 12);
                        },

                        checkRePassword: function() {
                            var user = $scope.user;
                            var re_password = user.re_password;

                            return re_password === postData['password'];
                        },

                        checkEmail: function() {
                            var user = $scope.user;
                            var email = user.email ? $.trim(user.email) : '';

                            postData['email'] = email;
                            return emailRegex.test(email);
                        },

                        checkCode: function() {
                            var user = $scope.user;
                            var code = user.code ? $.trim(user.code) : '';

                            postData['code'] = code;
                            return $scope.checkFieldLength(code, 1, 30);
                        },

                        checkUserInfo: function() {
                            if (!$scope.checkCode()) {
                                $scope.showFieldTooltip('#code');
                                return false;
                            }
                            if (!$scope.checkPassword()) {
                                $scope.showFieldTooltip('#password');
                                return false;
                            }

                            if (!$scope.checkRePassword()) {
                                $scope.showFieldTooltip('#re-password');
                                return false;
                            }

                            postData['subrole'] = $scope.user.subrole;
                            return true;
                        },

                        createUser: function() {
                            if (!$scope.checkUserInfo()) {
                                return false;
                            }

                            UserService.createNewAdmin({
                                'code': postData['code'],
                                'password': hex_md5(postData['password']),
                                'role': 'ADMIN',
                                'subrole': postData['subrole'],
                                'region': $scope.user.region.name || null
                            }).then(function(ret) {
                                if (ret.data.code) {
                                    alert(ret.data.value);
                                    return false;
                                };
                                alert('Create Successfully!');
                                $scope.closeDialog();
                                vm.loadData();
                            });
                        }
                    });
                }],
                scope: $scope
            });
        }

    })
    .controller('AccountCtrl', function($scope, $state, ngDialog, $window, HotelService, UserService, NgTableParams) {
        var vm = this;
        $scope.years = [2015, 2016];
        $scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

        if (!$scope.regions) {
            $scope.regions = [];
            HotelService.getRegions().then(function(ret) {
                if ($window.sessionStorage.subrole == 'Sub-Region Admin') {
                    angular.forEach(ret.data.value, function(value, key) {
                        if ($window.sessionStorage.region == value.name) {
                            $scope.regions.push(value);
                            vm.region.id = value.id;
                            vm.regionChange();
                        }
                    })
                } else {
                    $scope.regions = ret.data.value;

                }
            })
        }

        vm.year = 2016;
        vm.month = 1;

        vm.regionChange = function() {
            vm.cluster = null;
            vm.loadData();
            HotelService.getClusters(vm.region.id).then(function(ret) {
                $scope.clusters = ret.data.value;
            })
        }

        vm.clusterChange = function() {
            vm.loadData();
        }
        vm.loadData = function() {
            UserService.getAllAdminUsers().then(function(ret) {
                vm.result = ret.data;
                vm.tableParams = new NgTableParams({
                    count: 25
                }, {
                    dataset: vm.result
                });
            })
        }
        vm.loadData();

        vm.deleteUser = function(id) {
            if (confirm('确定要删除吗？')) {
                UserService.deleteAdminUser(id).then(function() {
                    alert('删除管理员用户成功！');
                    vm.loadData();
                });
            }

        };

        vm.editAdminUser = function(user) {
            ngDialog.open({
                template: 'views/admin/create_admin_user.html',
                ariaAuto: false,
                className: 'ngdialog-theme-plain custom-width',
                controller: ['$scope', 'ngDialog', function($scope, ngDialog) {
                    $scope.user = user;
                    $scope.user.passowrd = '';

                    $.extend($scope, {
                        closeDialog: function() {
                            ngDialog.closeAll();
                        },

                        createUser: function() {
                            UserService.saveAdmin({
                                'id': user.id,
                                'code': user.code,
                                'password': hex_md5(user.password),
                                'role': 'ADMIN',
                                'subrole': user.subrole,
                                'region': user.region.name || null
                            }).then(function(ret) {
                                if (ret.data.code) {
                                    alert(ret.data.value);
                                    return false;
                                };
                                alert("Edit Successfully！");
                                $scope.closeDialog();
                                vm.loadData();
                            });
                        }
                    });
                }],
                scope: $scope
            });
        };

        vm.createAdminUser = function() {
            $scope.user = {};
            ngDialog.open({
                template: 'views/admin/create_admin_user.html',
                ariaAuto: false,
                className: 'ngdialog-theme-plain custom-width',
                controller: ['$scope', 'ngDialog', function($scope, ngDialog) {
                    var postData = {};
                    var emailRegex = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g;

                    var mobileRegex = /^(13[0-9]{9})|(14[0-9])|(18[0-9])|(15[0-9][0-9]{8})$/;

                    $.extend($scope, {
                        closeDialog: function() {
                            ngDialog.closeAll();
                        },

                        checkFieldLength: function(field, start, end) {
                            return !(!field || field.length < start || field.length > end);
                        },

                        showFieldTooltip: function(selector) {
                            $(selector).popover('show');
                        },

                        closeFiledTooltip: function(selector) {
                            $(selector).popover('destroy');
                        },

                        closeAllTooltip: function() {
                            $scope.closeFiledTooltip('#password');
                            $scope.closeFiledTooltip('#re-password');
                            $scope.closeFiledTooltip('#email');
                            $scope.closeFiledTooltip('#mobile');
                        },

                        checkPassword: function() {
                            var user = $scope.user;
                            var password = user.password ? $.trim(user.password) : '';

                            postData['password'] = password;
                            return $scope.checkFieldLength(password, 3, 12);
                        },

                        checkRePassword: function() {
                            var user = $scope.user;
                            var re_password = user.re_password;

                            return re_password === postData['password'];
                        },

                        checkEmail: function() {
                            var user = $scope.user;
                            var email = user.email ? $.trim(user.email) : '';

                            postData['email'] = email;
                            return emailRegex.test(email);
                        },

                        checkCode: function() {
                            var user = $scope.user;
                            var code = user.code ? $.trim(user.code) : '';

                            postData['code'] = code;
                            return $scope.checkFieldLength(code, 1, 30);
                        },

                        checkUserInfo: function() {
                            if (!$scope.checkCode()) {
                                $scope.showFieldTooltip('#code');
                                return false;
                            }
                            if (!$scope.checkPassword()) {
                                $scope.showFieldTooltip('#password');
                                return false;
                            }

                            if (!$scope.checkRePassword()) {
                                $scope.showFieldTooltip('#re-password');
                                return false;
                            }

                            postData['subrole'] = $scope.user.subrole;
                            return true;
                        },

                        createUser: function() {
                            if (!$scope.checkUserInfo()) {
                                return false;
                            }

                            UserService.createNewAdmin({
                                'code': postData['code'],
                                'password': hex_md5(postData['password']),
                                'role': 'ADMIN',
                                'subrole': postData['subrole'],
                                'region': $scope.user.region ? $scope.user.region.name : null
                            }).then(function(ret) {
                                if (ret.data.code) {
                                    alert(ret.data.value);
                                    return false;
                                };
                                alert('Create Successfully!');
                                $scope.closeDialog();
                                vm.loadData();
                            });
                        }
                    });
                }],
                scope: $scope
            });
        }

    })
